import java.util.Arrays;

public class MyArrayList {//定义一个顺序表
    private int[] elem;//定义数组
    private int useSize;//有效数据个数
    private static int intCapacity = 10;//数组初始容量

    public MyArrayList() {//无参的构造方法
        this.elem = new int[intCapacity];
        this.useSize = 0;
    }

    //方法
    //1.打印顺序表
    public void display() {
        //System.out.println(Arrays.toString(this.elem));
        for (int i = 0; i < this.useSize; i++) {
            System.out.print(this.elem[i] + "  ");
        }
        System.out.println();
    }

    private boolean isFull() {//主要是提供给add的，所以设为私有的
        return this.useSize == this.elem.length;
    }

    private void checkPos(int pos) {//判断pos的位置是否合法
        if (pos < 0 || pos > this.useSize) {
            throw new RuntimeException("pos位置不合法！");
        }
    }

    //2.在pos位置新增元素data
    public void add(int pos, int data) {
        checkPos(pos);

        if (isFull()) {
            this.elem = Arrays.copyOf(this.elem, 2 * this.elem.length);//如果满了，对数组进行扩容
            //这一步只是创建了一个长度为2*elem.length的数组,复制了elem内的元素。
            //return;
        }
        {//挪动数据
            for (int i = this.useSize - 1; i >= pos; i--) {
                this.elem[i + 1] = this.elem[i];
            }
            this.elem[pos] = data;
            this.useSize++;
        }
    }

    //3.判断是否包含某个元素
    public boolean contains(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if (this.elem[i] == toFind) {
                return true;
            }
        }
        return false;
    }

    //4.查找某个元素的对应的位置
    public int search(int toFind) {
        for (int i = 0; i < this.useSize; i++) {
            if (this.elem[i] == toFind) {
                return i;
            }
        }
        return -1;
    }

    //5.获取pos位置的元素
    public int getPos(int pos) {
        //1.判断是否为空  -1
        //pos合法性
        if (this.useSize == 0) {
            //return -1;
            throw new RuntimeException("顺序表为空!");//手动抛出一个异常
        }
        if (pos < 0 || pos >= this.useSize) {
            return -1;
        }
        return this.elem[pos];
    }

    //6.获取顺序表长度
    public int size() {
        return this.useSize;
    }

    //7.删除第一次出现的关键字data
    public void toRemove(int data) {
        int index = search(data);
        if (index == -1) {
            System.out.println("没有要删除的元素！");
            return;
        }
        for (int i = index; i < this.useSize - 1; i++) {
            this.elem[i] = this.elem[i + 1];
        }
        this.useSize--;
    }

    //8.清空顺序表
    public void clear() {
        this.useSize = 0;
    }
    //9.更新顺序表
    public void update(int pos,int data){
        if (pos < 0 || pos >= this.useSize) {
            throw new RuntimeException("pos位置不合法！");
        }
        this.elem[pos]=data;
    }
}
